package com.chengshi.shop.schedule;

import com.chengshi.shop.model.order.Order;
import com.chengshi.shop.service.order.OrderHistoryService;
import com.chengshi.shop.service.order.OrderService;
import com.chengshi.shop.service.wechat.MessageService;
import com.chengshi.shop.util.EnumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 定时器任务管理
 *
 * @author xuxinlong
 * @version 2017年08月02日
 */
@Component
public class ScheduledTasks {
    @Resource
    private OrderService orderService;
    @Resource
    private OrderHistoryService orderHistoryService;
    @Resource
    private MessageService messageService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 订单关闭定时任务 每10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void closeOrder() {
        List<Order> list = orderService.getOverdueOrder();
        for (Order order : list) {
            if (order.getStatus() == EnumUtil.ORDER_STATUS.待付款.getValue().byteValue()) {
                orderService.closeOrder(order, "系统", "订单超时未支付，交易关闭");
                logger.info("关闭订单：" + order.getOrderNum() + "成功");
            }
        }
    }

    /**
     * 系统自动确认收货 每10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void receiptOrder() {
        List<Order> list = orderService.getCanReceiptOrder();
        for (Order order : list) {
            orderService.saveReceipt(order.getOrderId(), "系统");
            logger.info("确认收货：" + order.getOrderNum());
        }
    }

    /**
     * 系统自动查询快递信息 每60分钟执行一次
     *
     * @throws Exception
     */
    @Scheduled(cron = "0 0/60 * * * ?")
    public void getOrderHistory() throws Exception {
        HashMap<String, Object> inMap = new HashMap<>();
        inMap.put("status", EnumUtil.ORDER_STATUS.待收货.getValue());
        List<Order> list = orderService.getOrderList(inMap);
        for (Order order : list) {
            orderHistoryService.getListByOrderId(order.getOrderId());
            logger.info("查询物流成功：" + order.getOrderNum());
        }
    }

    /**
     * 通知管理员发货 每天上午10点执行
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void sendDeliveryNotice() {
        HashMap<String, Object> inMap = new HashMap<>();
        inMap.put("status", EnumUtil.ORDER_STATUS.待发货.getValue());
        List<Order> list = orderService.getOrderList(inMap);
        if (!list.isEmpty()) {
            messageService.sendDeliveryNotice(list.size());
        }
    }
}